package com.aizuda.easyManagerTool.service.monitor.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.aizuda.easy.security.domain.Rep;
import com.aizuda.easy.security.domain.Req;
import com.aizuda.easyManagerTool.domain.dto.PageDTO;
import com.aizuda.easyManagerTool.domain.entity.monitor.MonitorAlarmEntity;
import com.aizuda.easyManagerTool.domain.vo.PageVO;
import com.aizuda.easyManagerTool.domain.vo.setting.SettingUserVO;
import com.aizuda.easyManagerTool.mapper.monitor.MonitorAlarmMapper;
import com.aizuda.easyManagerTool.service.monitor.MonitorAlarmService;
import com.aizuda.easyManagerTool.service.setting.impl.alarm.AlarmStrategy;
import com.aizuda.easyManagerTool.util.AssertUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class MonitorAlarmServiceImpl extends ServiceImpl<MonitorAlarmMapper, MonitorAlarmEntity> implements MonitorAlarmService {

    @Resource
    private MonitorAlarmMapper monitorAlarmMapper;
    MonitorAlarmEntity monitorAlarmEntity = new MonitorAlarmEntity();
    @Resource
    AlarmStrategy alarmStrategy;
    ObjectMapper mapper = new ObjectMapper();

    @Override
    public Rep<PageVO<MonitorAlarmEntity>> find(Req<PageDTO<MonitorAlarmEntity>, SettingUserVO> req) {
        PageDTO<MonitorAlarmEntity> pageDTO = req.getData();
        Page<MonitorAlarmEntity> page = new Page<MonitorAlarmEntity>(pageDTO.getCurrent(), pageDTO.getSize());
        // 查询 唯一条件是要根据 权限查询
        MonitorAlarmEntity monitorAlarmEntity = pageDTO.getData() ;
        IPage<MonitorAlarmEntity> serverListEntrtyIPage = monitorAlarmMapper.find(page, ObjectUtil.isEmpty(monitorAlarmEntity)? new MonitorAlarmEntity():monitorAlarmEntity);
        PageVO<MonitorAlarmEntity> pageVO = new PageVO<MonitorAlarmEntity>(pageDTO)
                .setTotal(serverListEntrtyIPage.getTotal())
                .setRecords(serverListEntrtyIPage.getRecords());
        return Rep.ok(pageVO);
    }

    @Override
    public Rep<MonitorAlarmEntity> edit(Req<MonitorAlarmEntity, SettingUserVO> req) {
        MonitorAlarmEntity data = req.getData();
        SettingUserVO user = req.getUser();
        AssertUtil.objIsNull(data.getId(), "数据错误");
        if(data.getMaHandle()){
            data.setMaHandleUser(user.getId());
            data.setMaHandleTime(new Date());
        }
        monitorAlarmMapper.updateById(data);
        return Rep.ok();
    }

    @Override
    public Rep<MonitorAlarmEntity> del(Req<MonitorAlarmEntity, SettingUserVO> req) {
        MonitorAlarmEntity data = req.getData();
        SettingUserVO user = req.getUser();
        AssertUtil.objIsNull(data.getId(), "数据错误");
        monitorAlarmMapper.deleteById(data.getId());
        return Rep.ok();
    }

    @Override
    public void save(MonitorListManager.MonitorData data) {
        List<MonitorAlarmEntity> monitorAlarmEntities = new ArrayList<>();
        data.getDataIndex().stream().forEach(item -> {
            if(!item.getMdiAlarm()){
                return;
            }
            // 入库
            if(item.getCurrentFrequency().compareTo(item.getFrequency()) < 0){
                return;
            }
            item.setCurrentFrequency(0);
            MonitorAlarmEntity alarmEntity = BeanUtil.copyProperties(monitorAlarmEntity, MonitorAlarmEntity.class);
            alarmEntity.setMaTitle(item.getFullName());
            alarmEntity.setMaThreshold(item.getThreshold());
            alarmEntity.setMaFrequency(item.getFrequency());
            alarmEntity.setMaValue(item.getValue());
            alarmEntity.setTenantId(data.getTenantId());
            alarmEntity.setMaText(JSONUtil.toJsonStr(data.getJson()));
            monitorAlarmEntities.add(alarmEntity);
            try {
                alarmStrategy.send("监控告警",
                        "全称："+item.getFullName()+"\n"+
                            "阈值："+item.getThreshold()+"\n"+
                            "连续阈值："+item.getFrequency()+"\n"+
                            "告警值："+item.getValue()+"\n"+
                            "JSON快照：\n "+mapper.writerWithDefaultPrettyPrinter().writeValueAsString(data.getJson())+"\n"
                        , data.getTenantId());
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        });
        if(monitorAlarmEntities.size() > 0) {
            saveBatch(monitorAlarmEntities);
        }
    }


}
